<?php


namespace App\Admin\Services\Wechat;


use App\Admin\Exceptions\Wechat\CompanyMiniProgramException;
use App\Commons\WechatOpenPlatform\WechatOpenPlatformTool;
use App\Repositories\App\AppProjectRepository;
use App\Repositories\Wechat\MiniProgramTemplateRepository;

class CompanyMiniProgramService {
    /**
     * 获取授权连接
     *
     * @param CompanyMiniProgramService $service
     *
     * @return array
     */
    public function getComponentLoginPageUrl() {
        $callbackUrl = config('app.url') . '/api/open/wechat/authorization-callback';
        
        return [
            'component_login_page_url' => WechatOpenPlatformTool::getInstance()->getComponentLoginPageUrl($callbackUrl),
        ];
    }
    
    /**
     * 获取草稿列表
     * @return mixed
     */
    public function getDraftsList() {
        return WechatOpenPlatformTool::getInstance()->getDraftsList()['draft_list'];
    }
    
    /**
     * 获取模板列表
     * @return mixed
     */
    public function getTemplateList() {
        return WechatOpenPlatformTool::getInstance()->getTemplateList()['template_list'];
    }
    
    /**
     * 将草稿添加到模板中
     *
     * @param int $draftId
     *
     * @return mixed
     */
    public function createTemplateCreateFromDraft(int $draftId) {
        return WechatOpenPlatformTool::getInstance()->createTemplateCreateFromDraft($draftId);
    }
    
    /**
     * 删除指定魔板
     *
     * @param $templateId
     * @return mixed
     * @throws CompanyMiniProgramException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function deleteTemplate($templateId) {
        //查询本地模板的id
        $localTemplateEl = (new MiniProgramTemplateRepository())->getItemByConditions(
            ['wx_template_id' => $templateId],
            function ($query) {
                $query->select(['id']);
            }
        );
        if ($localTemplateEl->isNotEmpty()) {
            $localTemplateId = array_column($localTemplateEl->toArray(), 'id');
            //是否还有正常小程序绑定该模板，如果有则提示还不能删除
            $projectEl = (new AppProjectRepository())->getItemByConditions(['mpt_id' => $localTemplateId]);
            if ($projectEl->isNotEmpty()) {
                throw new CompanyMiniProgramException(1100001);
            }
        }

        return WechatOpenPlatformTool::getInstance()->deleteTemplate($templateId);
    }
}